define(['jquery','moment',],function ($,moment) {
    return {
        run: function() {
            //获取url中的参数
            function getUrlParam(name) {
                //构造一个含有目标参数的正则表达式对象
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                //匹配目标参数
                var r = window.location.search.substr(1).match(reg);
//返回参数值
                if (r != null) return unescape(r[2]); return null;
            }
            //用户名设置
            var   ClientName = localStorage.getItem("client_name");
            if(Math.random()*10 > 2 || ClientName==null){
                ClientName = '访客——';
                while(ClientName.length<8){
                    var   ranNum = Math.ceil(Math.random() * 25);
                    ClientName +=String.fromCharCode(65+ranNum);
                }
                localStorage.setItem("client_name",ClientName);
            }
            //localStorage.clear()
            console.log(ClientName);


            var API = 'https://bing.ioliu.cn/v1/rand?type=json&w=240';
            var defaultAvatar = "s";

            var Avatar = localStorage.getItem("avatar");
            if(Math.random()*10>2 || Avatar==null){
                $.ajax({
                    url:API,
                    dataType:"jsonp",
                    jsonp: "callback",
                    jsonpCallback:"aaa",
                    success:function(data){
                        if(data.data.url){
                            localStorage.setItem("avatar",data.data.url);
                        }else{
                            localStorage.setItem("avatar",defaultAvatar);
                        }
                    }
                });
            }

            //通讯聊天  start
            var User = {
                VISITOR:"visitor",
                ADMIN:"admin",
                ClientName:ClientName,
                Avatar:Avatar,
                RoomId:"user_1_site_1",
                AdminAvatar:null
            }

            //事件绑定 eventBind
            var EventBind = {
                init:function(){
                    $('#sendMsg').click(function(e){
                        e.preventDefault();
                        var inputDom = $('#sendContent');
                        userSay(inputDom .val());
                        inputDom.val('');
                        inputDom.focus();
                    })
                }
            }
            EventBind.init();

            var GlobalData = {
                ToClientId:null,
                ToClientName:null,
            }



            function scrollToBottom(){
                $('#chat-box').scrollTop(10000);
            }


            if (typeof console == "undefined") {    this.console = { log: function (msg) {  } };}
            // 如果浏览器不支持websocket，会使用这个flash自动模拟websocket协议，此过程对开发者透明
            WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
            // 开启flash的websocket debug
            WEB_SOCKET_DEBUG = true;
            var ws, name, client_list={};

            connect();
            // 连接服务端
            function connect() {
                // 创建websocket
                ws = new WebSocket("ws://"+document.domain+":7272");
                // 当socket连接打开时，输入用户名
                ws.onopen = onopen;
                // 当有消息时根据消息类型显示不同信息
                ws.onmessage = onmessage;
                ws.onclose = function() {

                    connect();
                };
                ws.onerror = function() {
                    console.log("出现错误");
                };
            }

            // 连接建立时发送登录信息
            function onopen()
            {

                var login_data = '{"room_id":"user_1_site_1","role":"visitor","avatar":"'+Avatar+'","type":"login","client_name":"'+ClientName+'"}';
                console.log("websocket握手成功，发送登录数据:"+login_data);
                ws.send(login_data);
                say('连接成功');
            }

            // 服务端发来消息时
            function onmessage(e)
            {
                console.log(e.data);
                var data = JSON.parse(e.data);
                console.log(data);
                switch(data['type']){
                    // 服务端ping客户端
                    case 'ping':
                        ws.send('{"type":"pong"}');
                        break;;
                    // 登录 更新用户列表
                    case 'login':
                        var role = data.role;
                        switch (data.role){
                            case User.ADMIN:
                                User.AdminAvatar = data.avatar;
                                break;
                            case User.VISITOR:
                                var key = Object.keys(data.client_info)[0];
                                User.AdminAvatar = key ? data.client_info[key].avatar : 'http://www.sucaijishi.com/uploadfile/2016/0203/20160203022635285.png';
                                GlobalData.ToClientId = key
                                GlobalData.ToClientName = data.client_info[key].client_name
                        }
                        //{"type":"login","client_id":xxx,"client_name":"xxx","client_list":"[...]","time":"xxx"}
                        //say(data['client_id'], data['client_name'],  data['client_name']+' 加入了聊天室', data['time']);
                        if(data['client_list'])
                        {
                            client_list = data['client_list'];
                        }
                        else
                        {
                            client_list[data['client_id']] = data['client_name'];
                        }
                        //flush_client_list();
                        console.log(data['client_name']+"登录成功");
                        break;
                    // 发言
                    case 'say':
                        //{"type":"say","from_client_id":xxx,"to_client_id":"all/client_id","content":"xxx","time":"xxx"}
                        say(data['content']);
                        break;
                    // 用户退出 更新用户列表
                    case 'logout':
                        //{"type":"logout","client_id":xxx,"time":"xxx"}
                        say(data['from_client_id'], data['from_client_name'], data['from_client_name']+' 退出了', data['time']);
                        delete client_list[data['from_client_id']];
                        flush_client_list();
                }
            }

            // 输入姓名
            function show_prompt(){
                name = prompt('输入你的名字：', '');
                if(!name || name=='null'){
                    name = '游客';
                }
            }

            // 提交对话
            function onSubmit() {
                var input = document.getElementById("textarea");
                var to_client_id = $("#client_list option:selected").attr("value");
                var to_client_name = $("#client_list option:selected").text();

                var html = '<div class="speech_item reserve"><img src="'+User.Avatar+'" class="user_icon"> '+User.ClientName+' <br> '+(new Date())+'<div style="clear:both;"></div><p class="triangle-isosceles top">'+input.value+'</p> </div>';
                $('#dialog').append(html);
                input.value = "";
                input.focus();
            }

            // 刷新用户列表框
            function flush_client_list(){
                var userlist_window = $("#userlist");
                var client_list_slelect = $("#client_list");
                userlist_window.empty();
                client_list_slelect.empty();
                userlist_window.append('<h4>在线用户</h4><ul>');
                client_list_slelect.append('<option value="all" id="cli_all">所有人</option>');
                for(var p in client_list){
                    userlist_window.append('<li id="'+p+'">'+client_list[p]+'</li>');
                    client_list_slelect.append('<option value="'+p+'">'+client_list[p]+'</option>');
                }
                $("#client_list").val(select_client_id);
                userlist_window.append('</ul>');
            }

            // 发言
            function say(content){
                var chatBox = $('#chat-box');
                var time = moment().format("HH:mm:ss");
                var html = '<figure role="group" class="msg tripla"><!----> <p>'+content+'</p>\n' +
                    '    <figcaption><span class="avatar"\n' +
                    '                      style="background-image: url(&quot;https://s3-ap-northeast-1.amazonaws.com/umami-imagehoteltriplabot/201/medium/32cbc5c4e4bac5c0f965aef08da758105b746d97.jpg?1530261474&quot;);"></span>\n' +
                    '        Web Site\n' +
                    '        <time datetime="2018-09-25T23:16:13.000+09:00">'+time+'</time>\n ' +
                    // '        <ul role="aria-hidden" class="eval">\n' +
                    // '            <li>有帮助吗？</li>\n' +
                    // '            <li></li>\n' +
                    // '            <li></li>\n' +
                    // '        </ul>\n' +
                    '    </figcaption>\n' +
                    '</figure>';
                chatBox.append(html);
            }


            function userSay(content){
                ws.send('{"avatar":"'+User.Avatar+'","client_name":"'+User.ClientName+'","room_id":"'+User.RoomId+'","type":"say","role":"visitor", "to_client_id":"'+GlobalData.ToClientId+'","to_client_name":"'+GlobalData.ToClientName+'","content":"'+content.replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r')+'"}');
                var chatBox = $('#chat-box');
                var time = moment().format("HH:mm:ss");
                var html ='<figure role="group" class="msg cust"><p class="user-balloon" style="background-color: rgb(0, 161, 168); color: rgb(255, 255, 255);">' +
                    '                '+content+'</p> ' +
                    '            <figcaption>' +
                    '\n' +
                    '                <time datetime="2018-09-25T23:14:43.000+09:00">'+time+' </time> <!----></figcaption>' +
                    '        </figure>';
                chatBox.append(html);

                scrollToBottom();
            }

            $(function(){
                select_client_id = 'all';
                $("#client_list").change(function(){
                    select_client_id = $("#client_list option:selected").attr("value");
                });
                $('.face').click(function(event){
                    $(this).sinaEmotion();
                    event.stopPropagation();
                });
            });

            //document.write('<meta name="viewport" content="width=device-width,initial-scale=1">');
            $("textarea").on("keydown", function(e) {
                // 按enter键自动提交
                if(e.keyCode === 13 && !e.ctrlKey) {
                    e.preventDefault();
                    $('form').submit();
                    return false;
                }

                // 按ctrl+enter组合键换行
                if(e.keyCode === 13 && e.ctrlKey) {
                    $(this).val(function(i,val){
                        return val + "\n";
                    });
                }
            });
        },
    };
});